<template>
  <div style="padding: 15px" v-loading="pageLoading">
    <div class="filter-container">
      <el-select class="filter-item" multiple @change="search2" style="width: 220px; margin-left: 5px"
        :style="{ width: getWidth }" v-model="machine" placeholder="选择设备名称">
        <el-option v-for="i in allMachine" :key="i.value" :label="i.label" :value="i.value"></el-option>
      </el-select>
      <el-select class="filter-item" @change="search1" style="width: 220px; margin-left: 5px" v-model="type"
        placeholder="选择设备类型">
        <el-option v-for="i in MachineType" :key="i.value" :label="i.label" :value="i.value"></el-option>
      </el-select>
      <div style="width: 360px; margin-left: 5px;margin-right:5px" class="filter-item">
        <el-date-picker v-model="timeRange" type="daterange" style="width:100%" range-separator="~" start-placeholder="时间"
          end-placeholder="范围" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" @change="search3" />
      </div>
      <el-button @click="getData" class="filter-item" type="primary">查询</el-button>
    </div>
    <template v-if="data.length">
      <h3 >{{ type }}设备多天甘特图</h3>
      <div ref="ganttChart" style="width: 100%;" class="ganttChart"></div>
    </template>
    <template v-else>
      <el-empty description="暂无数据,请选择筛选条件进行数据查询"></el-empty>
    </template>
    <template v-if="data.length">
      <hr />
      <h3>工时统计</h3>
      <div ref="statsChart"  style="width: 100%; height: 300px;"></div>
    </template>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import dayjs from 'dayjs';
export default {
  name: 'MachineShiftEcharts',
  data() {
    return {
      min: null,
      max: null,
      timeRange:[
        dayjs().format('YYYY-MM-DD 00:00:00'),
        dayjs().add(14, 'day').format('YYYY-MM-DD 00:00:00')
      ],
      pageLoading: false,
      type: null,
      machine: [],
      MachineType: [
        { value: '配粉', label: '配粉设备' },
        { value: '气流磨', label: '气流磨设备' },
        { value: '混粉', label: '混粉设备' },
        { value: '压机', label: '压机设备' },
        { value: '烧结炉', label: '烧结炉设备' },
      ],
      allMachine: [],
      data:[],
      typeColors: { 正常上班: '#4caf50', 休息: '#2196f3' },
    };
  },
  mounted() {
    this.getDictionary();
  },
  computed: {
    getWidth() {
      if (this.machine?.length === 0 || this.machine == null) return '200px';
      else if (this.machine?.length > 0 && this.machine?.length < 5)
        return this.machine?.length * 200 + 'px';
      return '800px';
    },
  },
  methods: {
    getDictionary() {
      this.http.post('api/Sys_Dictionary/GetVueDictionary', ['BASE_Machine_Prd']).then((r) => {
        this.allMachine = r[0].data.map((i) => ({
          value: i.key,
          label: i.value,
        }));
      });
    },
    search1() {
      this.machine = null;
      this.getData();
    },
    search2() {
      if (!this.machine.length) {
        this.data = []
        return 
      }
      this.type = null;
      this.getData();

    },
    search3(){
      if(!this.timeRange) {
        this.min = dayjs().format('YYYY-MM-DD 00:00:00')
        this.max = dayjs().add(14,'day').format('YYYY-MM-DD 00:00:00')
      }
      this.getData()

    },
    getData() {
      if(!this.type && !this.machine.length) return this.$message.error('请选择设备或设备类型')
      let ids = [];
      if (!this.type) {
        ids = this.machine;
      } else if (!this.machine) {
        ids = this.allMachine.filter((i) => i.label.includes(this.type)).map((i) => i.value);
      }
      this.pageLoading = true;
      this.http
        .post('api/Aps_MachineShift/getPageData', {
          page: 1,
          rows: 9999,
          wheres: JSON.stringify([{ name: 'MachineId', displayType: 'selectList', value: ids.join(',') }, { name: 'StartTime', displayType: 'thanorequal', value: this.timeRange[0] }, { name: 'StartTime', displayType: 'lessorequal', value: this.timeRange[1] }]),
        })
        .then((r) => {
          this.data = r.rows.map((i) => ({
            device: this.allMachine.find((j) => j.value === i.MachineId).label,
            startTime: i.StartTime,
            endTime: i.EndTime,
            Hours: i.Hours,
            type: i.ClockInType === 1 ? '正常上班' : '休息',
          }));
          this.min = this.data.reduce(
            (acc, item) => Math.min(acc, this.parseTime(item.startTime)),
            Infinity
          );
          this.max = this.data.reduce(
            (acc, item) => Math.max(acc, this.parseTime(item.endTime)),
            -Infinity
          );
          this.$nextTick(()=>{

            this.initCharts();
          })
        })
        .finally(() => {
          this.pageLoading = false;
        });
    },
    parseTime(time) {
      return new Date(time.replace(' ', 'T')).getTime();
    },
    initCharts() {
      const devices = [...new Set(this.data.map((item) => item.device))];
      const ganttSeries = {
        type: 'custom',
        renderItem: (params, api) => {
          const categoryIndex = api.value(0);
          const start = api.coord([api.value(1), categoryIndex]);
          const end = api.coord([api.value(2), categoryIndex]);
          const height = api.size([0, 1])[1] * 0.6;

          return {
            type: 'rect',
            shape: { x: start[0], y: start[1] - height / 2, width: end[0] - start[0], height },
            style: api.style(),
          };
        },
        data: this.data.map((item) => [
          devices.indexOf(item.device),
          this.parseTime(item.startTime),
          this.parseTime(item.endTime),
          this.typeColors[item.type],
          item.type,
        ]),
        encode: { x: [1, 2], y: 0 },
        itemStyle: {
          color: (params) => params.value[3],
        },
      };

      const ganttOption = {
        tooltip: {
          formatter: (params) => {
            const item = this.data[params.dataIndex];
            return `设备: ${item.device}<br>开始时间: ${item.startTime}<br>结束时间: ${item.endTime}<br>类型: ${item.type}<br>工时: ${item.Hours}分钟`;
          },
        },
        xAxis: {
          type: 'time',
          min: this.min,
          max: this.max,
          axisLabel: { formatter: (val) => dayjs(val).format('MM-DD HH:mm') },
          splitLine: { show: true } // 显示分割线
        },
        yAxis: {
          type: 'category',
          data: devices,
          inverse: true,
          axisLabel: {
            fontSize: 10,
          },
        },
        yAxis: { type: 'category', data: devices, inverse: true },
        dataZoom: [{ type: 'slider', xAxisIndex: 0, start: 0, end: 100 }, {
          type: 'slider',
          yAxisIndex: 0,
          start: 0,
          end: 100,
        },],
        series: [ganttSeries],
      };


      const statsData = devices.map((device) => {
        const totalWorkTime = this.data
          .filter((item) => item.device === device && item.type === '正常上班')
          .reduce((acc, item) => acc + item.Hours, 0);
        return { name: device, value: totalWorkTime };
      });

      const statsOption = {
        tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c}分钟 ({d}%)' },
        legend: {
          orient: 'vertical',
          right: '1%',
          top: '10%',
          bottom: '10%',
          itemWidth: 20,
          itemHeight: 14,
          itemGap: 10,
          textStyle: {
            fontSize: 12,
          },
        },
        series: [
          {
            name: '工时分布',
            type: 'pie',
            radius: ['40%', '70%'],
            label: { formatter: '{b}: {d}%' },
            data: statsData,
            center: ['35%', '50%'],
          },
        ],
      };

      const ganttChart = echarts.init(this.$refs.ganttChart);
      ganttChart.setOption(ganttOption);

      const statsChart = echarts.init(this.$refs.statsChart);
      statsChart.setOption(statsOption);
    },
  },
};
</script>

<style >
.ganttChart {
  height: calc(100vh - 300px);
}
</style>